This template shows you how to make a map given a numeric or categorical data item with a geographic id and a shape file with the same ID.
Inputs required: a data table with a field to map and an ID, a geographic layer with a matching ID
User options: Legend tile, Legend subtitle color ramo
library(sf) # geographic data library
library(dplyr) # for working with data frames
library(psrcelmer) # to get data from Elmer
library(psrcplot) # to get color schemes
library(htmltools)
library(htmlwidgets)
library(mapview)
library(psrccensus)
Sys.getenv("CENSUS_API_KEY")
This R file has a function called create_psrc_map to create a leaflet map for you these are the function inputs: lyr: sf map layer, the geographic layer including the field you want to map lyr_data_field: string, the name of data field you want to map legend_title: string, The title in the legend legend_subtitle: string, The title in the legend psrc_col_pal: string list, color ramp map_lat=47.615, map_lon=-122.257: defaults, can be overridden for centering the map map_zoom=8.5, wgs84=4326 : defaults, can be overriden, zoom level and projection
source('map_region.R')
Prepare data to join with the geographic layer Note: you will need field names to match on This example gets ACS 5-year data for Asian Groups by Tract.
big_tbl <-psrccensus::get_acs_recs(geography='tract',table.names='B02015',year=2021, acs.type='acs5')
# read in data table and process data to join and map
tbl <- big_tbl %>%filter(label=='Estimate!!Total:!!Vietnamese')%>%
dplyr::select(GEOID,estimate) %>%
dplyr::mutate(dplyr::across(c('GEOID'), as.character))%>%
dplyr::group_by(GEOID) %>%
dplyr::summarise(Total=sum(estimate))
tract_layer_name <- "TRACT2020_NOWATER"
lyr <- st_read_elmergeo(tract_layer_name)
lyr_data<- dplyr::left_join(lyr,tbl, by = c("geoid20"="GEOID"))
# this is the field to map
lyr_datafield<-lyr_data$Total
# need to add a white color to ensure contrast
psrc_purple_plus<-append(psrc_colors$purples_inc, "#FFFFFF", after=0)
map_it<-create_psrc_map(lyr=lyr_data,
lyr_data_field=lyr_data_field,
legend_title= 'Vietnamese Population',
legend_subtitle = 'by Census Tract',
psrc_col_pal=psrc_purple_plus)
map_it
mapshot(map_it, url= "VietnamesePop.html")
mapshot(map_it, file= "VietnamesePop.png")